import app from '@/app'
import { ref, reactive } from 'vue'
import store from '@/app/store'
import { get, create } from '@/api/provider/fiskaly_ticket'
import { provider } from '@/api/store/order_ticket'

// 初始化
const ticketStore = store()

// 分页
ticketStore.page = reactive({
  current: 1,
  pageSize: 0,
  total: 0,
  showPageSize: false,
  loading: false
})

// 查询类型
ticketStore.where = reactive({ 
  key: 'number', 
  value: ''
})

// 生成查询数据
ticketStore.getWhere = () => {
  // 查询方式
  const where = { [ticketStore.where.key]: ticketStore.where.value }
  // 合并数据
  return Object.assign(where, ticketStore.getData())
}

ticketStore.get = () => {
  return new Promise((resolve, jeject) => {
    ticketStore.page.loading = true
    get(ticketStore.getWhere()).then(res => {
      const list = res.data.map(item => {
        item.created_at = app.time.load(item.created_at)
        item.data.created_at = app.time.load(item.data.created_at)
        return item
      })
      ticketStore.setList(list)
      // 分页
      ticketStore.page.current = res.current_page
      ticketStore.page.pageSize = res.per_page
      ticketStore.page.total = res.total
      resolve(res)
    }).catch(res => {
      jeject(res)
    }).finally(() => {
      ticketStore.page.loading = false
    })
  })
}

ticketStore.create = (id) => {
  return new Promise((resolve, jeject) => {
    create(id).then(res => {
      provider(id, 'fiskaly', 1)
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

// 重置请求
ticketStore.reset = page => {
  ticketStore.page.current = page
  ticketStore.getData().page = page

  // 开始加载
  ticketStore.get()
}

export default ticketStore